package cn.itsource.ymcc.producer;

import cn.itsource.ymcc.common.constant.RocketConstants;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.CourseOrderItem;
import cn.itsource.ymcc.service.ICourseOrderItemService;
import cn.itsource.ymcc.service.ICourseOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

//保存课程订单以及支付订单的事务消息
@Component
@Slf4j
@RocketMQTransactionListener(
        txProducerGroup = RocketConstants.MQ_COURSEORDER_PAY_GROUP_TRANSACTION
)
public class CourseOrderTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService iCourseOrderService;
    @Autowired
    private ICourseOrderItemService courseOrderItemService;
    /**
     * 执行本地事务
     * @param message
     * @param o
     * @return
     */
    @Override
    @Transactional
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            Map<String,Object> map = (Map<String, Object>)o;
            courseOrderItemService.saveBatch((List<CourseOrderItem>)map.get("list"));
            iCourseOrderService.saveOrUpdate((CourseOrder) map.get("courseOrder"));
        }catch (Exception e){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //执行有问题
        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     * 检查本地事务  有没有执行
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //去查询数据库
        return RocketMQLocalTransactionState.COMMIT;
    }
}
